package com.rent.wechat.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import reactor.core.publisher.Mono;

import java.util.concurrent.CompletableFuture;

/**
 * @Author zhang
 * @create 2022/9/13 16:50
 */
@Slf4j
public class CustomBlockingLoadBalancerClient extends BlockingLoadBalancerClient {

    private final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerClientFactory;

    public CustomBlockingLoadBalancerClient(ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerClientFactory) {
        super(loadBalancerClientFactory);
        this.loadBalancerClientFactory = loadBalancerClientFactory;
    }


    @Override
    public ServiceInstance choose(String serviceId) {
        return super.choose(serviceId);
    }

    @Override
    public <T> ServiceInstance choose(String serviceId, Request<T> request) {
        ReactiveLoadBalancer<ServiceInstance> loadBalancer = loadBalancerClientFactory.getInstance(serviceId);
        if (loadBalancer == null) return null;
        CompletableFuture<Response<ServiceInstance>> future = CompletableFuture.supplyAsync(() -> Mono.from(loadBalancer.choose(request)).block());
        Response<ServiceInstance> loadBalanceResponse = null;
        try {
            loadBalanceResponse = future.get();
        } catch (Exception e) {
           log.info("自定义服务异常:{}",e.getMessage());
        }
        if (loadBalanceResponse == null) return null;
        return loadBalanceResponse.getServer();
    }

}
